<?php
namespace app\api\controller;
use app\api\controller\BaseController;
use app\api\model\Order as Orders;
use app\api\model\OrderShop;
use app\api\model\Shop;
use app\api\model\UserShoping;
use app\api\model\Member;
use app\api\model\ShopSpecification;
use extend\Alipay\aop\AopClient;
use think\Request;
use think\Db;

class Order extends BaseController
{
	/**
	 * 生成订单
	 * @param  Orders $orders [description]
	 * @return [type]         [description]
	 */
	public function order(Orders $orders, ShopSpecification $shop_spec)
	{
		return $this->setError('该商品暂时无法购买');
		if(!input('post.user_id') || !input('post.order_addr') || !input('post.buyer_name') || !input('post.user_iphone')|| !input('post.order_money')) {
			return $this->setError('参数不能为空');
		}
		Db::startTrans();
		try {
			if(input('post.buyer_message')) {
				$post['buyer_message'] = input('post.buyer_message'); //备注
			}
			$order_info['order_money'] = '';
			$freight = '';
			if(input('post.shop_id')) {
				$order_info = $this->getShopInfo(input('post.shop_id'));
				$order_info['order_money'] = sprintf("%1.2f", $order_info['shop_end_money']  * input('post.shop_num') + $order_info['freight']);
				$freight = $order_info['freight'];
			} else {
				$cart = explode(',', input('post.cart_id'));
				foreach ($cart as $key => $value) {
					$order['shop'][$key] = $this->getUserShoping($value, 1);  //1查询。2修改

					$shop_list[] = $order['shop'][$key]['shop_id'];
					if($key == '0') {
						$order_freight[$key] = $this->getShopInfo($order['shop'][$key]['shop_id']);
						$freight += $order_freight[$key]['freight'];
					} else {
						if(!in_array($order['shop'][$key]['shop_id'], $shop_list)) {
							$order_freight[$key] = $this->getShopInfo($order['shop'][$key]['shop_id']);
							$freight += $order_freight[$key]['freight'];
						}
					}
					
				}
				foreach ($order['shop'] as $value) {
					$order_info['order_money'] += $value['shop_price'] * $value['shop_num'];
				}
				$order_info['order_money'] = $order_info['order_money'] + $freight;
			}
			$post['order_number'] = date('Ymd', time()) . $this->getRange(2) . date('His', time()); //订单编号
			$post['create_time'] = time();
			$post['order_money'] = sprintf("%1.2f", $order_info['order_money']);
			$post['order_staff'] = 1;
			$post['order_addr'] = input('post.order_addr');
			$post['buyer_name'] = input('post.buyer_name');
			$post['buyer_phone'] = input('post.user_iphone');
			$post['user_id'] = input('post.user_id');
			$post['order_use'] = 0;
			$post['pay_status'] = 2;
			if($freight) {
				$post['freight'] = sprintf("%1.2f", $freight);
			}
			$result = $orders->save($post);
			if(!$result) {
				throw new \Exception('生成订单失败');
			}
			$freight = '0';
			if(input('post.shop_id')) {
				$order_shop = new OrderShop();
				$shop_specs = $shop_spec->where(['id' => input('post.shop_spec_id')])->field('spec_one_name, spec_two_name')->select()->toArray(); 
				$shop['shop_id'] = input('post.shop_id');
				$shop['shop_name'] = $order_info['shop_name'];
				$shop['member_id'] = '1';
				$shop['member_name'] = '华联可溯商城';
				$shop['order_number'] = $post['order_number'];
				$shop['spec'] = json_encode($shop_specs[0], JSON_UNESCAPED_UNICODE);
				$shop['shop_num'] = input('post.shop_num');
				$shop['shop_price'] = sprintf("%1.2f", $order_info['shop_end_money']);
				$shop['shop_total'] = sprintf("%1.2f", ($order_info['shop_end_money'] * input('post.shop_num')));
				$shop_query = $order_shop->save($shop);
				if(!$shop_query) {
					throw new \Exception('订单商品添加失败');
				}
			} else {
				foreach ($order['shop'] as $key => $value) {
					$order_shop = new OrderShop();
					$shop_info = $this->getShopInfo($value['shop_id']);
					$shop['shop_id'] = $value['shop_id'];
					$shop['shop_name'] = $value['shop_name'];
					$shop['member_id'] = $value['member_id'];
					$shop['member_name'] = $value['member_name'];
					$shop['order_number'] = $post['order_number'];
					$shop['spec'] = $value['shop_spec'];
					$shop['shop_num'] = $value['shop_num'];
					$shop['shop_price'] = sprintf("%1.2f", $shop_info['shop_end_money']);
					$shop['shop_total'] = sprintf("%1.2f", ($shop_info['shop_end_money'] * $value['shop_num']));
					$shop_query = $order_shop->save($shop);
					if(!$shop_query) {
						throw new \Exception('订单商品添加失败');
					}
				}
				foreach ($cart as $key => $value) {
					$is_use = $this->getUserShoping($value, 2);
				}
			}
			Db::commit();      
		} catch (Exception $e) {
			Db::rollback();
			return $this->setError($e->getmessage());
		}
		return $this->setSuccess($post['order_number']);
		
	}
	/**
	 * 获取购物车
	 * @param  [type] $shop_id [description]
	 * @return [type]          [description]
	 */
	public function getShopInfo($shop_id)
	{
		$shop = new Shop();
		$result = $shop->where(['id' => $shop_id])->field('shop_name, member_id, member_name, shop_end_money, freight')->select()->toArray();
		if(!$result) {
			return [];
		}
		return $result[0];
	}
	public function getUserShoping($cart_id, $type)
	{
		$user_shoping = new UserShoping();
		if($type == '1') {
			$result = $user_shoping->where(['id' => $cart_id])->select()->toArray();
			if($result) {
				return $result[0];
			}
		} else if($type == '2') {
			$result = $user_shoping->where(['id' => $cart_id])->update(['is_use' => 1]);
		}
		
		
	}
	/**
	 * 结算订单
	 * @return [type] [description]
	 */
	public function orderSettlement(Orders $orders)
	{
		
		$order_num = input('post.order_num');
		if(!$order_num) {
			return $this->setError('参数不能为空');
		}
		Db::startTrans();
		try {
			$order_settelement = $orders->where(['order_number' => $order_num])->update(['pay_status' => '1', 'pay_time' => time()]);
			if(!$order_settelement) {
				throw new \Exception('支付失败');
			}
			$order = $orders->where(['order_number' => $order_num])->select()->toArray();
			$member = new Member();
			$members = $member->where(['id' => 1])->select()->toArray();
			$result = $member->where(['id' => 1])->update(['money' => $members[0]['money'] + $order[0]['order_money']]);
			if(!$result) {
				throw new \Exception('商家收钱失败');
			}
			$order_shop = new OrderShop();
			$order_shops = $order_shop->where(['order_number' => $order_num])->select()->toArray();
			for ($i=0; $i < count($order_shops) ; $i++) { 
				$order_shop_query = $order_shop->where(['id' => $order_shops[$i]['id']])->update(['staff' => 1]);
				if(!$order_shop_query){
					throw new \Exception('订单商品状态修改失败');
				}
			}
		 	Db::commit(); 
		} catch (Exception $e) {
			Db::rollback();
			return $this->setError($e->getmessage());
		}
		return $this->setSuccess('支付成功');
	}
	/**
	 * 获取随机2位数
	 * @param  [type] $len [description]
	 * @return [type]      [description]
	 */
	private function getRange($len)
	{
		$chars = array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");   
    	$charsLen = count($chars) - 1;   
    	shuffle($chars);     
    	$output = "";   
    	for ($i=0; $i<$len; $i++) {   
        	$output .= $chars[mt_rand(0, $charsLen)];   
    	}   
    	return $output;  
	}
}